package com.rzx.mybackend.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzx.mybackend.common.PageResult;
import com.rzx.mybackend.config.rabbitMQ.mqMsg.GamePublishMsg;
import com.rzx.mybackend.dto.GamePageDTO;
import com.rzx.mybackend.entity.Game;
import com.rzx.mybackend.entity.GamePublishTask;
import com.rzx.mybackend.enums.games.GamesStatus;
import com.rzx.mybackend.enums.tasks.GamePublishTaskStatus;
import com.rzx.mybackend.mapper.GameMapper;
import com.rzx.mybackend.service.GamePublishTaskRecordService;
import com.rzx.mybackend.service.GameService;
import com.rzx.mybackend.utils.OssUtil;
import com.rzx.mybackend.utils.RabbitMQUtils;
import com.rzx.mybackend.utils.TimeStampUtils;
import com.rzx.mybackend.vo.GameDetailsVO;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

/**
 * GameServiceImpl
 *
 * @author renzhexian
 * @date 2025/7/16
 */
@Service
@RequiredArgsConstructor
public class GameServiceImpl implements GameService {

    private static final Logger log = LoggerFactory.getLogger(GameServiceImpl.class);

    private final GameMapper gameMapper;

    private final OssUtil ossUtil;

    private final RabbitMQUtils rabbitMQUtils;

    private final GamePublishTaskRecordService gamePublishTaskRecordService;

    @Resource(name = "commonTaskExecutor")
    private Executor commonTaskExecutor;

    @Getter
    private final ConcurrentHashMap<Long,GamePublishTask> gameTasksConcurrentHashMap = new ConcurrentHashMap<>();
    private final GamePublishTaskRecordServiceImpl gamePublishTaskRecordServiceImpl;

    @Value("${spring.rabbitmq.gamePublish.exchange_name}")
    private String GAME_PUBLISH_DELAY_EXCHANGE;

    @Value("${spring.rabbitmq.gamePublish.routing_key}")
    private String GAME_PUBLISH_DELAY_ROUTING_KEY;

    /**
     * 内存管理
     * 新增任务
     */
    @Override
    public void updateGamePublishTask(Long gameId, GamePublishTask task) {
        gameTasksConcurrentHashMap.put(gameId, task);
    }

    /**
     * 内存管理
     * 删除任务
     * @param gameId 游戏ID
     */
    @Override
    public void deleteGamePublishTask(Long gameId) {
        gameTasksConcurrentHashMap.remove(gameId);
    }

    /**
     * 内存管理
     * 获取任务
     * @param gameId 游戏ID
     * @return GamePublishTask
     */
    @Override
    public GamePublishTask getGamePublishTask(Long gameId) {
        return gameTasksConcurrentHashMap.get(gameId);
    }

    /*
    分页查询游戏列表
     */
    @Override
    public PageResult pageGameList(GamePageDTO gamePageDTO) {
        //开始分页
        PageHelper.startPage(gamePageDTO.getPage(), gamePageDTO.getPageSize());

        //查询游戏列表
        Page<Game> gamePage = gameMapper.query(gamePageDTO);

        return new PageResult(gamePage.getTotal(),gamePage.getResult());
    }

    /*
    上传文件到aliyunOss,并更新数据库
     */
    @Transactional
    @Override
    public void updateGamePicture(Long gameId, MultipartFile file) throws IOException {
        // 上传图片到阿里云OSS
        String fileUrl = null;
        try {
            fileUrl = ossUtil.uploadFile(file, "gamePicture");
        } catch (IOException e) {
            throw new RuntimeException("上传游戏图片失败", e);
        }

        log.info("上传游戏图片成功，文件URL: {}", fileUrl);

        // 更新数据库中的游戏图片URL
        gameMapper.updateGamePicture(gameId, fileUrl);
    }

    /*
    上传游戏视频
     */
    @Transactional
    @Override
    public void updateGameVideo(Long gameId, MultipartFile file) {

        // 上传视频到阿里云OSS
        String fileUrl = null;
        try {
            fileUrl = ossUtil.uploadFile(file, "gameVideo");
        } catch (IOException e) {
            throw new RuntimeException("上传游戏图片失败", e);
        }

        log.info("上传游戏视频成功，文件URL: {}", fileUrl);

        // 更新数据库中的游戏图片URL
        gameMapper.updateGameVideo(gameId, fileUrl);
    }

    /**
     * 根据游戏ID获取游戏信息
     * @param gameId
     * @return
     */
    @Override
    public Game getGameById(Long gameId) {
        return gameMapper.selectById(gameId);
    }

    /**
     * 更新游戏信息
     * @param game
     */
    @Transactional
    @Override
    public void updateGame(Game game) {
        Game gameById = this.getGameById(game.getId());
        // 从内存中获取任务
        GamePublishTask gamePublishTask = gameTasksConcurrentHashMap.get(game.getId());
        // todo: 修改当前游戏这个版本号的任务，更新任务状态为已取消
        LambdaUpdateWrapper<GamePublishTask> gamePublishTaskLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        gamePublishTaskLambdaUpdateWrapper
                .eq(GamePublishTask::getGameId, game.getId())
                .eq(GamePublishTask::getVersion, gamePublishTask)
                .set(GamePublishTask::getTaskStatus, GamePublishTaskStatus.CANCELED.getCode());

        // 修改内存中的版本号
        String currentVersion = TimeStampUtils.getCurrentTimestamp() + game.getGameCode();
        gamePublishTask.setVersion(currentVersion);
        gamePublishTask.setCreateTime(LocalDateTime.now().toString());
        gameTasksConcurrentHashMap.put(game.getId(), gamePublishTask);

        // todo: 把新任务添加到数据库中
        gamePublishTaskRecordService.save(gamePublishTask);

        // 判断是否需要重新发送MQ消息
        if (needResendMQ(game, gameById)){
            // 需要重新发送MQ消息
            rabbitMQUtils.sendMessage(GAME_PUBLISH_DELAY_EXCHANGE, GAME_PUBLISH_DELAY_ROUTING_KEY, game);
        }

        gameMapper.updateById(game);
    }

    /**
     * 判断是否需要重新发送MQ消息
     * 如果状态为待上架且上架时间有变化，则需要重新发送MQ消息
     * @param game
     * @param gameById
     * @return
     */
    private static boolean needResendMQ(Game game, Game gameById) {
        return gameById.getStatus().equals(GamesStatus.TO_BE_SHELVED.getCode()) && !game.getOnshelfDate().equals(gameById.getOnshelfDate());
    }

    /*
    根据游戏ID删除游戏
     */
    @Override
    public void deleteGame(Long gameId) {
        cancelPublishBaseMemory(gameId);
        gameMapper.deleteGame(gameId);
    }

    private void cancelPublishBaseMemory(Long gameId) {
        // 将内存中任务状态置为已取消
        GamePublishTask gamePublishTask = getGamePublishTask(gameId);
        gamePublishTask.setTaskStatus(GamePublishTaskStatus.CANCELED.getCode());
        updateGamePublishTask(gameId, gamePublishTask);
    }

    /*
    根据游戏ID获取游戏详情
     */
    @Override
    public GameDetailsVO getGameDetails(Long gameId) {

        return gameMapper.selectDetailsByGameId(gameId);
    }

    /*
    处理延迟添加游戏
     */
    @Transactional
    @Override
    public void handleDelayAddGame(Game game) {

        gameMapper.insert(game);

        String currentTimestamp = TimeStampUtils.getCurrentTimestamp()+game.getGameCode();

        // 将添加游戏任务加入内存管理 <游戏ID,任务类>
        GamePublishTask task = GamePublishTask.builder()
                .gameStatus(GamesStatus.TO_BE_SHELVED.getCode())
                .taskStatus(GamePublishTaskStatus.ING.getCode())
                .gameId(game.getId())
                .createTime(LocalDateTime.now().toString())
                .version(currentTimestamp)
                .build();
        gameTasksConcurrentHashMap.put(game.getId(), task);
        log.info("内存添加游戏任务成功");

        // todo: 异步记录任务到数据库
        commonTaskExecutor.execute(() -> gamePublishTaskRecordServiceImpl.save(task));

        ObjectMapper objectMapper = new ObjectMapper();

        log.info("开始添加游戏: {}", game);

        Date onshelfDate = game.getOnshelfDate();

        long delayTime = getDelayTime(onshelfDate);

        try {
            // 创建消息属性并设置延迟时间

            GamePublishMsg gamePublishMsg = new GamePublishMsg();
            gamePublishMsg.setGame(game);
            gamePublishMsg.setVersion(currentTimestamp);

            MessageProperties properties = new MessageProperties();
            properties.setDelayLong(delayTime);

            Message message = MessageBuilder
                    .withBody(objectMapper.writeValueAsString(gamePublishMsg).getBytes())
                    .andProperties(properties)
                    .build();

            rabbitMQUtils.sendMessage(
                    GAME_PUBLISH_DELAY_EXCHANGE,
                    GAME_PUBLISH_DELAY_ROUTING_KEY,
                    message);

            log.info("发送延迟消息成功，游戏ID: {}", game.getId());

        } catch (JsonProcessingException e) {
            log.error("序列化失败", e);
            throw new RuntimeException("序列化失败！");
        }

    }

    /**
     * 获取延迟时间
     * @param onshelfDate
     * @return
     */

    private static long getDelayTime(Date onshelfDate) {

        log.info("上架时间: {}", onshelfDate.getTime());
        // 计算延迟时间（毫秒）
        long delayTime = onshelfDate.getTime() - System.currentTimeMillis();

        // 确保延迟时间不为负数
        if (delayTime <= 0) {
            log.warn("上架时间早于当前时间，立即发送消息");
            delayTime = 0;
        }
        return delayTime;
    }
}
